/** 现货市场  伏羲储能 */
import { yunNao } from "@src/api/yunNao"
import { arrHasVal, getPrivateCommonParams } from "../data"
import { requestSDspotMarketZcq } from "@src/api/fetch"
import dayjs from "dayjs"
import { AsyncRecursion, CbParams, creatAsyncRecursion } from '@src/utils/asyncRecursion'
import { promisetTimeOut } from '@src/utils/common'
import { betweenStartEndDays } from "@src/entries/options/generate"


// 【现货市场】-【现货交易】-【实时交易结果】-【实时交易结果查询（正式数据）】 出清电价
/**
 * <select class="form-control" id="jylx">
								<option value="ALL">所有品种</option>
								<option value="SCSBXS">市场双边协商</option>
								<option value="SCSBGP">市场双边挂牌</option>
								<option value="DXHYY">月度集中交易</option>
								<option value="DXHYZ">月内集中交易</option>
								<option value="JSSBXS">月内滚动撮合交易</option>
								<option value="JSJZJZ">月度滚动撮合交易</option>
						</select>
 */
const typeList = [
  {
    name: '所有品种',
    value: 'ALL'
  },
  {
    name: '市场双边协商',
    value: 'SCSBXS'
  },
  {
    name: '市场双边挂牌',
    value: 'SCSBGP'
  },
  {
    name: '月度集中交易',
    value: 'DXHYY'
  },
  {
    name: '月内集中交易',
    value: 'DXHYZ'
  },
  {
    name: '月内滚动撮合交易',
    value: 'JSSBXS'
  },
  {
    name: '月度滚动撮合交易',
    value: 'JSJZJZ'
  }
]

enum TypeId {
  ALL = 1,
  SCSBXS = 2,
  SCSBGP,
  DXHYY,
  DXHYZ,
  JSSBXS,
  JSJZJZ,
}

let draw = 1
/**
 * 【现货市场】-【现货环境下中长期交易】-【电量信息详情查询】-【电量刻度信息详情查询】
 * 单日单个品种 
 */
type GetSaveOneTypeTradeInfoParams = {headers:HeadersInit, unitid:string, certainDate:string, jylx:string, errBreak?:boolean}
export const getSaveOneTypeTradeInfo = async ({headers, unitid, certainDate, jylx}:GetSaveOneTypeTradeInfoParams) => {
  console.log('【现货市场】-【现货环境下中长期交易】-【电量信息详情查询】-【电量刻度信息详情查询】')
  console.log('getSaveOneTypeTradeInfo', certainDate, typeList.find(item => item.value === jylx)?.name, TypeId?.[jylx as any])
  try {
    const formParams = new URLSearchParams({
      draw: String(++draw),
      start: String(0),
      length: String(96)
    })
  
    const dataObj = await requestSDspotMarketZcq(
      `https://pmos.sd.sgcc.com.cn:18080/zcq/dlxxxqcx96/dlxxxqYhCx.do?method=get96CjTableData&dyid=${unitid}&userProp=1&sDate=${certainDate}&eDate=${certainDate}&jylx=${jylx}`,
      formParams,
      { method:'POST', headers }
    )

    const quans = (dataObj?.data || []).map((item:any) => item?.cjdl || '')
    const prices = (dataObj?.data || []).map((item:any) => item?.cjjj || '')
    
    const tradeCateId = TypeId?.[jylx as any] || ''

    const dataList:Array<any> = [
      {
        date: certainDate, //固定yyyy-MM-dd
        tradeCateId,
        dataType: 1, // 1 净合约量;  2  平均成本;
        values: quans.length ? quans : Array.from({length:96}).fill(null)	 //96点格式
      },
      {
        date: certainDate,
        tradeCateId,
        dataType: 2,
        values: prices.length ? prices : Array.from({length:96}).fill(null)	 //96点格式
      }
    ]

    console.log('dataList', dataList)
    return Promise.resolve(dataList)
  
  } catch(e) {
    console.error(e)
  }
}

/** 所有品种, 单天 */
const getSaveOneDayTradeInfo = async (params:Omit<GetSaveOneTypeTradeInfoParams, 'jylx'>) => {
  try {
    const paramsList:GetSaveOneTypeTradeInfoParams[] = typeList.map(({value}) => ({...params, jylx:value}))

    const oneDayList:CbParams = await creatAsyncRecursion(AsyncRecursion, {
      stepAsyncFnParamsList: paramsList,
      stepAsyncFn: getSaveOneTypeTradeInfo,
      stepCb: async () => await promisetTimeOut(100), // 每隔 发出请求，防反爬
      stepAsyncNum: 1,
      errBreak: params?.errBreak
    }).start()

    return Promise.resolve((oneDayList?.allResultList || []).flat())
  }catch(e) {
    console.error(e)
  }
}

/**
 * 所有品种, 多天
 * @param dates 默认 undefined 不请求； []空数组，请求当月;
 * @param params Omit<GetSaveOneTypeTradeInfoParams, 'jylx' | 'certainDate'>
 * @returns
 */
let getSaveAllDayTradeInfoRunning = false
export const getSaveAllDayTradeInfo = async (dates:string[] | undefined = undefined, params:Omit<GetSaveOneTypeTradeInfoParams, 'jylx' | 'certainDate'>, errBreak = false) => {
  if(!dates) return Promise.resolve()

  if(getSaveAllDayTradeInfoRunning) {
    console.error('getSaveAllDayTradeInfo 正在运行中，无法再次启动！ 请稍后再试！')
    return Promise.resolve()
  }

  getSaveAllDayTradeInfoRunning = true

  const {unitid} = params

  try {
    let [startDate = '', endDate = ''] = dates
    if(!startDate || !endDate) [startDate, endDate] = [dayjs().startOf('month').format('YYYY-MM-DD'), dayjs().endOf('month').format('YYYY-MM-DD')]
  
    const paramsList = betweenStartEndDays(startDate,endDate).map((certainDate) => ({...params, certainDate, errBreak}))
  
    const allDayDataList:CbParams = await creatAsyncRecursion(AsyncRecursion, {
      stepAsyncFnParamsList: paramsList,
      stepAsyncFn: getSaveOneDayTradeInfo,
      stepCb: async () => await promisetTimeOut(1000), // 每隔 发出请求，防反爬
      stepAsyncNum: 1,
      errBreak
    }).start()

    const saveDataList = {
     ...getPrivateCommonParams({thirdId:unitid}),
     itemCode: 'medium_trade_info',
     dataList:(allDayDataList?.allResultList || []).flat().filter(item => arrHasVal(item?.values || []))
    }
    
    console.log('存储数据：getSaveAllDayTradeInfo', saveDataList)
    if(saveDataList.dataList.some(item => arrHasVal(item.values))) {
      await yunNao.saveJson(saveDataList)
      console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"))
    } else {
      console.log('无数据 不存')
    }
  }catch(e) {
    console.error(e)
  }finally {
    getSaveAllDayTradeInfoRunning = false
  }
}